package org.scratchcrew.services;

import org.scratchcrew.domain.BoardData;
import org.scratchcrew.domain.Scratch;
import org.scratchcrew.domain.ScratchData;
import org.scratchcrew.domain.dao.BoardDataDao;
import org.scratchcrew.domain.dao.ScratchDao;
import org.scratchcrew.domain.dao.ScratchDataDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service(value = "scratchService")
public class ScratchServiceImpl implements ScratchService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private BoardDataDao boardDataDao;
	@Autowired
	private ScratchDao scratchDao;
	@Autowired
	private ScratchDataDao scratchDataDao;

	@Override
	public String createScratch(Long boardId, String staticData,
			String scratchData) {
		BoardData boardData = boardDataDao.findByBoardId(boardId);
		if (boardData == null) {
			logger.warn("Cannot find boardData for board with id " + boardId);
			return null;
		}
		logger.info(String.format("Creating Scratch %s for board with id %d",
				staticData, boardId));
		boardDataDao.save(boardData);
		Scratch scratchEntity = new Scratch();
		scratchEntity.setBoardData(boardData);
		scratchEntity.setStaticData(staticData);
		scratchDao.save(scratchEntity);
		ScratchData scratchDataEntity = new ScratchData();
		scratchDataEntity.setScratchData(scratchData);
		scratchDataEntity.setScratch(scratchEntity);
		scratchDataDao.save(scratchDataEntity);
		return String.valueOf(scratchEntity.getId());
	}

	@Override
	public String findScratchData(Long scratchId) {
		ScratchData scratchDataEntity = scratchDataDao
				.findByScratchId(scratchId);
		String scratchData = scratchDataEntity.getScratchData();
		return scratchData;
	}

	@Override
	public void updateScratchData(String scratchData, Long scratchId) {
		ScratchData scratchDataEntity = scratchDataDao
				.findByScratchId(scratchId);
		scratchDataEntity.setScratchData(scratchData);
		scratchDataDao.save(scratchDataEntity);
	}

	@Override
	public void delete(Long id) {
		Scratch scratch = scratchDao.find(id);
		scratchDao.delete(scratch);
	}

	@Override
	public Scratch find(Long id) {
		return scratchDao.find(id);
	}

}
